function inArray(arr, key, val) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
            return i;
        }
    }
    return -1;
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('');
}
// 字符串转byte
function stringToBytes(str) {
    var array = new Uint8Array(str.length);
    for (var i = 0, l = str.length; i < l; i++) {
        array[i] = str.charCodeAt(i);
    }
    console.log(array);
    return array.buffer;
};
Page({
    data:{
        devices: [],
        showConnect: true,
        IsConnect:false,
        showTips:false,
        REQdata:[],
        chs:[],
        name:'',
        deviceId:''

    },
    //配对成功：跳转到主页； 
    done: function () {
        wx.navigateTo({
            url: '../index/index'
        });
    },
    //点击连接蓝牙事件
    createBLEConnection: function (e) {
        this.createBLEConnection(e);
        this.setData({
            IsConnect: true,
            showConnect: true
        });
    },
    /** 
    *蓝牙API: 
    * 1.初始化蓝牙（判断蓝牙是否可用）；openBluetoothAdapter
    * 2.获取蓝牙设备状态（蓝牙是否打开）；getBluetoothAdapterState
    * 3.监控蓝牙打开/关闭的动作；onBluetoothAdapterStateChange
    * 4.开始搜索周围是否有设备；startBluetoothDevicesDiscovery
    * 5.获取周围设备列表；getBluetoothDevices
    * 6.停止搜索周围设备，减少消耗资源；stopBluetoothDevicesDiscovery
    * 7.过滤目标设备；
    * 8.是否已经连接蓝牙设备：
    *           a.获取已经连接的蓝牙设备；getConnectedBluetoothDevices
    *           b.创建新的低功耗蓝牙设备连接deviceId；createBLEConnection
    * 9.获取设备的信息
    *           a.获取蓝牙设备的服务码；getBLEDeviceServices
    *           b.获取蓝牙设备的特征值；getBLEDeviceCharacteristics
    *           c.获取蓝牙设备的write和notify服务；readBLECharacteristicValue
    * 10.向蓝牙设备写入指令；writeBLECharacteristicValue
    * 11.只有，开启蓝牙设备的notify提醒功能；notifyBLECharacteristicValueChange
    * 12.才能，监听接受蓝牙设备返回的数据；onBLECharacteristicValueChange
    * 13.断开低功耗的蓝牙连接；closeBLEConnection
    * 14.关闭蓝牙，释放资源：closeBluetoothAdapter
    * 
    * */

    // 
    onLoad:function(){
        let _this=this;
        _this.BLEAdapter();
        _this.setData({
            IsConnect: wx.getStorageSync('IsConnect'),
            deviceId:wx.getStorageSync('DeviceId'),
            name:wx.getStorageSync('Name')
        });
        // wx.getConnectedBluetoothDevices({
        //     success: function (res) {
        //         that.writeBLECharacteristicValue();
        //     },
        // })
        // wx.onBLEConnectionStateChange(function(res) {
        //     if(res.connected){
        //         console.log('11')
        //         _this.BLEAdapter();
        //         _this.setData({
        //             IsConnect: true,
        //             deviceId:wx.getStorageSync('DeviceId'),
        //             name:wx.getStorageSync('Name')
        //         });
        //     }else{
        //         console.log('00')
        //         _this.BLEAdapter();
        //     }
        // });
    },
    onShow:function(){
         
        // let _this=this;
        // let deviceId = wx.getStorageSync('DeviceId');
        _this.setData({
            IsConnect: wx.getStorageSync('IsConnect'),
            deviceId:wx.getStorageSync('DeviceId'),
            name:wx.getStorageSync('Name')
        });
      
        // _this.BLEAdapter();
        // wx.onBLEConnectionStateChange(function(res) {
        //     if(res.connected){
        //         // _this.IsConnect();
        //         _this.setData({
        //             IsConnect: true,
        //             deviceId:deviceId,
        //         });
        //     }else{
        //         _this.createBLEConnections(deviceId);
              
        //     }
        // });
      },
       //方法：连接设备
  createBLEConnections(deviceId){
    let _this=this;
    wx.createBLEConnection({
        deviceId: deviceId,
        success: (res) => {
            _this.setData({
                IsConnect:true
            })
            console.log('连接成功', res);
            this.getBLEDeviceServices(deviceId);
            wx.setStorageSync('IsConnect', true);
            wx.stopBluetoothDevicesDiscovery({
                success:res=>console.log(res),
                fail:res=>console.log(res),
            })
        }
    });
},
    /**
     * 第一部分：蓝牙设配器
     * 1.微信小程序：是否支持
     * 2.手机蓝牙：是否可用；
     * 3.手机蓝牙：是否开启
     * 4.监听开启手机蓝牙状态的事件
     * 
     */ 
    //方法：蓝牙是否可用
    openBluetoothAdapter(){
        let _this=this;
        wx.openBluetoothAdapter({
            success: function (res) {
                console.log('openBluetoothAdapter success', res)
                _this.getBluetoothAdapterState();
            },
            fail(res){
                console.log('openBluetoothAdapter fail', res)
                wx.showModal({
                    title: '提示',
                    content: '请开启蓝牙设备',
                    success: function(res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                        } else if (res.cancel) {
                            console.log('用户点击取消');
                        }
                    }
                });
                wx.onBluetoothAdapterStateChange(function(res) {
                    if(res.available){
                      setTimeout(function(){
                          _this.openBluetoothAdapter()
                      },500);
                    }
                });
            }
        });        
    },
    //方法：蓝牙是否开启
    getBluetoothAdapterState(){
        let _this=this;
        wx.getBluetoothAdapterState({
            success: (res) => {
                console.log('getBluetoothAdapterState', res) ;
                _this.BLESeach();//开始搜索
            },
            fail(res) {
                console.log('getBluetoothAdapterState fail', res);
            }
        })  
    },
    BLEAdapter(){
        // 1.微信小程序：是否支持；
        if(!wx.openBluetoothAdapter){
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            });
          return;
        };
        // 2.手机蓝牙：是否可用；// 3.手机蓝牙：是否开启// 4.监听开启手机蓝牙状态的事件
        this.openBluetoothAdapter();
    },
     /**
     * 第二部分：开启搜索、过滤、连接、关闭搜索
     * 1.搜索设备；
     * 2.获取设备列表；
     * 3.连接设备，成功后关闭实时搜索；
     *
     * */
    // 方法：开始搜索周围是否有设备；
    startBluetoothDevicesDiscovery() {
        let _this=this;
        wx.startBluetoothDevicesDiscovery({
            allowDuplicatesKey: true,
            success: (res) => {
                console.log('startBluetoothDevicesDiscovery success', res)
                wx.onBluetoothDeviceFound(res=>{
                    let devices = res.devices;
                    // let mac = wx.getStorageSync('DeviceId');
                    // //情况1：已经连接过设备
                    // //情况2：第一次搜索设备；
                    // if(mac){
                    //     for(let i = 0;i<devices.length;i++){
                    //         if(devices[i].deviceId == mac){
                    //           console.log("find");
                    //           wx.stopBluetoothDevicesDiscovery({
                    //             success:res=>console.log(res),
                    //             fail:res=>console.log(res),
                    //           })
                    //         }
                    //     }
                    // }else{
                        res.devices.forEach(device => {
                            if (!device.deviceId) {
                                wx.showModal({
                                    title: '提示',
                                    content: '未搜索到设备。'
                                });
                                return
                            }else{
                                let IsBICQ=device.name.indexOf('BICQ')!=-1;
                                if(IsBICQ){
                                    const foundDevices = this.data.devices
                                    const idx = inArray(foundDevices, 'deviceId', device.deviceId)
                                    const data = {};
                                    if (idx === -1) {
                                        data[`devices[${foundDevices.length}]`] = device
                                    } else {
                                        data[`devices[${idx}]`] = device
                                    };
                                    _this.setData(data);
                                }
                            }
                        });
                    // };
                   
                })
            },
            fail(res) {
                console.log('startBluetoothDevicesDiscovery fail', res)
            }
        })
    },
    //方法：连接设备
    createBLEConnection(e){
        let _this=this;
        let ds = e.currentTarget.dataset;
        let deviceId = ds.deviceId;
        wx.setStorageSync('DeviceId', ds.deviceId);
        wx.setStorageSync('Name', ds.name);
        wx.createBLEConnection({
            deviceId: deviceId,
            success: (res) => {
                console.log('连接成功', res);
                this.getBLEDeviceServices(deviceId);
                wx.setStorageSync('IsConnect', true);
                _this.setData({
                    showConnect: false,
                    showTips: true,
                });
                wx.stopBluetoothDevicesDiscovery({
                    success:res=>console.log(res),
                    fail:res=>console.log(res),
                  })
            }
        });
    },
    BLESeach(){
       this.startBluetoothDevicesDiscovery();
    },
     /**
     * 第三部分：服务值、特征、write和notify服务
     * 1.获取服务值；
     * 2.特征；
     * 3.write和notify服务
     * 
     * */
    //方法：服务值
    getBLEDeviceServices(deviceId){
        let _this=this;
        wx.getBLEDeviceServices({
            deviceId:deviceId,
            success: (res) => {
                for (let i = 0; i < res.services.length; i++) {
                    // 注：解析过程出现两个service，第二个是以前使用的，所以这里添加判断
                    if (res.services[i].uuid.indexOf("6E400001") != -1) {
                        if (res.services[i].isPrimary) {
                            wx.setStorageSync('ServiceId', res.services[i].uuid);
                            _this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
                            return
                        }
                    }
                };
            },
            fail(res) {
                console.log('获取服务码错误：', res)
            }
        });
    },
    //方法：write和notify服务
    getBLEDeviceCharacteristics(deviceId, serviceId) {
        let _this=this;
        wx.getBLEDeviceCharacteristics({
            deviceId:deviceId,
            serviceId:serviceId,
            success: (res) => {
                console.log('getBLEDeviceCharacteristics success', res.characteristics)
                for (let i = 0; i < res.characteristics.length; i++) {
                    let item = res.characteristics[i]
                    if (item.properties.read) {
                        wx.readBLECharacteristicValue({
                            deviceId:deviceId,
                            serviceId:serviceId,
                            characteristicId: item.uuid,
                        })
                    }
                    if (item.properties.write) {
                        wx.setStorageSync('CharacteristicId', item.uuid);
                        _this.writeBLECharacteristicValue();//先同步
                    }
                    if (item.properties.notify || item.properties.indicate) {
                        wx.notifyBLECharacteristicValueChange({
                            deviceId:deviceId,
                            serviceId:serviceId,
                            characteristicId: item.uuid,
                            state: true,
                            complete(res) {
                                _this.onBLECharacteristicValueChange();//接受消息
                               
                              }
                        })
                    }
                }
            },
            fail(res) {
                console.error('getBLEDeviceCharacteristics', res)
            }
        })
    },
     /**
     * 第四部分：向蓝牙写入指令、监控接受数据
     * 1.写入指令；
     *     对应命令转为16进制的形式
     *      START   = [83, 84, 65, 82, 84]+时间戳
     *      STOP    = [83, 84, 79, 80]
     *      REQDATA = [82, 69, 81, 68, 65, 84, 65]
     *      AUTO_ACC= [   ...]    
     * 2.监控接收数据；
     * 
     * */
    //方法同步
    writeBLECharacteristicValue(){
        let _this=this;
        let order="REQDATA";
        let  buffer = stringToBytes(order);
        let deviceId = wx.getStorageSync('DeviceId');
        let serviceId = wx.getStorageSync('ServiceId');
        let characteristicId = wx.getStorageSync('CharacteristicId');
        wx.writeBLECharacteristicValue({
            deviceId: deviceId,
            serviceId: serviceId,
            characteristicId: characteristicId,
            value: buffer,
            success: function (res) {
                console.log("同步成功", res)
                 _this.writeBLECharacteristicValueSTART()
            },
            fail(res) {
                console.log("发送失败", res)
            }
        })
    }, 
    // 开始start
    writeBLECharacteristicValueSTART(){
        let  dtTime= Date.parse(new Date())/1000;//时间戳：秒
        let  order="START"+dtTime;
        let  buffer = stringToBytes(order);
        let deviceId = wx.getStorageSync('DeviceId');
        let serviceId = wx.getStorageSync('ServiceId');
        let characteristicId = wx.getStorageSync('CharacteristicId');
        wx.writeBLECharacteristicValue({
            deviceId: deviceId,
            serviceId: serviceId,
            characteristicId: characteristicId,
            value: buffer,
            success: function (res) {
                console.log("开始成功", res)
            },
            fail(res) {
                console.log("发送失败", res)
            }
        })
    }, 
    //方法接受消息
    onBLECharacteristicValueChange(){
        let _this=this;
        wx.onBLECharacteristicValueChange((characteristic) => {
            
            // const idx = inArray(_this.data.chs, 'uuid', characteristic.characteristicId); 
            // _this.data.REQdata.push(ab2hex(characteristic.value));
            // console.log('监听同步返回数据index',ab2hex(characteristic));
            // console.log('同步单个数据index',ab2hex(characteristic.value));
            // console.log('同步数据数组参数index', _this.data.REQdata);
            if (characteristic.value.byteLength == 3){
                wx.hideLoading();
                wx.request({
                  url: 'https://ssldev.imreliable.com:5010/handRing/updataDTing', //仅为示例，并非真实的接口地址
                    data: {
                        HandRingMac: wx.getStorageSync('DeviceId'),
                        DataStreams: this.data.REQdata
                    },
                    method:'POST',
                    header: {
                        'content-type': 'application/json' // 默认值
                    },
                    success: function(res) {
                        wx.setStorageSync("ReqData", res.data)
                         
                        _this.writeBLECharacteristicValueSTART()//再开始
                        console.log('先同步再开始',res.data);
                    },
                    fail: (res) => {
                        console.log(res.data);
                    },
                });
                return;
            };
        })
    },
            
    /**
     * 第五部分：断开、释放资源
     * 1.断开蓝牙
     * 2.关闭释放蓝牙资源
     * 
     * */
    closeBLEConnection(){
        wx.closeBLEConnection({
            deviceId: device_id,
            success(res) {
              console.log(res)
            },
            fail(res) {
              console.log(res)
            }
          });
        wx.closeBluetoothAdapter({
            success: function (res) {
              console.log(res)
            }
        })
    }
    
})


